<template>
  <el-card class="box-card">
    <div class="icon-container1" @click="flip">
      <el-icon color="rgba(255, 255, 255, 0.7)">
        <Refresh />
      </el-icon>
    </div>
    <el-row class="index-container" justify="center">
      <el-col :span="8" v-for="index in indexQuotations" v-bind:key="index.f12">
        <div style="font-weight: bold;">{{index.f14}}</div>
        <div :style="{color: getColor(index.f4),'font-weight': 'bold','font-size': '22px'}">{{(index.f2/100).toFixed(2)}}</div>
        <el-row>
          <el-col :span="12" :style="{color: getColor(index.f4)}">{{(index.f4/100).toFixed(2)}}</el-col>
          <el-col :span="12" :style="{color: getColor(index.f4)}">{{(index.f3/100).toFixed(2)+'%'}}</el-col>
        </el-row>
      </el-col>
    </el-row>
    <el-divider v-show="!enableSearch" />
    <div class="icon-container2" :style="{padding: !enableSearch?'4px 0':0}">
      <el-icon color="rgba(255, 255, 255, 0.8)" :size="20" class="icon1" @click="enableSearch=!enableSearch" v-show="!enableSearch&&!enableEdit&&!enablePic"><Search /></el-icon>
      <el-icon color="rgba(255, 255, 255, 0.8)" :size="20" class="icon2" @click="enablePic=!enablePic" v-show="!enableSearch&&!enableEdit&&!enablePic"><Picture /></el-icon>
      <el-icon color="rgba(255, 255, 255, 0.8)" :size="20" class="icon3" @click="enableEdit=!enableEdit" v-show="!enableSearch&&!enableEdit&&!enablePic"><Edit /></el-icon>
      <el-icon color="rgba(255, 255, 255, 0.8)" :size="20" class="icon4" @click="enablePic=false;enableEdit=false" v-show="!enableSearch&&(enableEdit||enablePic)"><Grid /></el-icon>
      <el-row  v-show="enableSearch" class="search-container">
        <el-icon color="rgba(255, 255, 255, 0.8)" :size="20" @click="enableSearch=!enableSearch" class="icon5"><back /></el-icon>
        <el-input v-model="inputValue" placeholder="输入证券代码、名称、简拼或关键字" class="input" clearable>
          <template #prefix>
            <el-icon class="el-input__icon"><Search style="width: 300px;" /></el-icon>
          </template>
        </el-input>
      </el-row>
    </div>
    <el-row class="th" v-if="enableSearch">
      <el-col :span="5">代码</el-col>
      <el-col :span="10">名称</el-col>
      <el-col :span="5">证券类型</el-col>
      <el-col :span="4">添加</el-col>
    </el-row>
    <el-row class="th" v-else v-show="!enablePic">
      <el-col :span="5">名称</el-col>
      <el-col :span="5">昨收</el-col>
      <el-col :span="5">今开</el-col>
      <el-col :span="5">最新</el-col>
      <el-col :span="4">{{!enableEdit?'涨跌幅':'移除'}}</el-col>
    </el-row>
    <div class="tbody" :style="{'border-radius':enablePic?'5px':'0 0 5px 5px'}">
      <div class="container-out" :style="{height:!enablePic?'185px':'220px'}">
        <div class="container-in" :style="{'right':-scrollBarWidth+'px'}">
          <el-row class="tr" v-for="instrument in quotations" v-bind:key="instrument.f12" v-show="!enableSearch&&!enablePic">
            <el-col class="td1" :span="5">{{getInstrumentName(instrument.f14)}}</el-col>
            <el-col class="td2" :span="5">{{formatValue(instrument.f12, instrument.f18)}}</el-col>
            <el-col class="td3" :span="5" :style="{color:getColor(instrument.f17-instrument.f18)}">{{formatValue(instrument.f12, instrument.f17)}}</el-col>
            <el-col class="td4" :span="5" :style="{color:getColor(instrument.f2-instrument.f18)}">{{formatValue(instrument.f12, instrument.f2)}}</el-col>
            <el-col class="td5" :span="4" :style="{color:getColor(instrument.f3)}" v-show="!enableEdit">{{formatPercent(instrument.f3)}}</el-col>
            <el-col class="td5" :span="4" v-show="enableEdit">
              <el-icon color="rgba(255, 255, 255, 0.7)" class="icon6" @click="removeInstrument(instrument.f12)"><delete-filled /></el-icon>
            </el-col>
          </el-row>
          <el-row class="tr" v-for="instrument in queryResult" v-bind:key="instrument.Code" v-show="enableSearch">
            <el-col :span="5">{{instrument.Code}}</el-col>
            <el-col :span="10">{{getQueryInstrumentName(instrument.Name)}}</el-col>
            <el-col :span="5">{{instrument.SecurityTypeName}}</el-col>
            <el-col :span="4">
              <el-icon color="rgba(255, 255, 255, 0.7)" class="icon7" :size="19" @click="addInstrument(instrument)" v-show="showQueryItem(instrument)"><circle-plus /></el-icon>
              <div v-show="!showQueryItem(instrument)">已添加</div>
            </el-col>
          </el-row>
          <el-row v-show="enablePic&&!enableSearch">
            <div v-for="(instrument, index) in instruments" v-bind:key="instrument.quoteId" >
              <div>{{instrument.name}}</div>
              <el-image style="margin: 5px;" :preview-src-list="imgSrcs" :initial-index="index" :src="instrument.imgUrl"></el-image>
            </div>
          </el-row>
        </div>
      </div>
    </div>
    <el-row style="margin-top: 10px;">
      <div v-show="!enableSearch">{{'更新时间：'+updateTime}}</div>
    </el-row>
  </el-card>
</template>

<script>
import axios from 'axios'
import moment from 'moment'
import {
  Refresh, Search, Picture, Edit, Grid, Back, DeleteFilled, CirclePlus
} from '@element-plus/icons-vue'

export default {
  name: "StockBack",
  props: {
    flipFlag: Boolean
  },
  components: {
    Refresh,
    Search,
    Picture,
    Edit,
    Grid,
    Back,
    DeleteFilled,
    CirclePlus
  },
  data() {
    return {
      scrollBarWidth: 15,
      inputValue: '',
      instruments: [],
      queryResult: [],
      indexQuotations: [],
      quotations: [],
      intervalId: '',
      updateTime: '',
      enableSearch: false,
      enablePic: false,
      enableEdit: false
    }
  },
  mounted() {
    window.ipcRenderer.sendSync('zoomFactor', null,
        (zoomFactor) => this.scrollBarWidth = this.scrollBarWidth / zoomFactor)
    this.listInstruments()
  },
  watch: {
    enableSearch(val) {
      if (val) {
        this.inputValue = ''
        this.queryResult = []
      }
    },
    inputValue(val) {
      this.queryInstruments(val)
    },
    flipFlag(val) {
      if (val) {
        this.listQuotations()
        this.intervalId = setInterval(() => {
          const now = new moment()
          const time = parseInt(now.format('HHmm'))
          const week = now.format('dddd')
          if ((time >= 915 && time <= 1140 || time >= 1250 && time <= 1510) && week !== 'Saturday' && week !== 'Sunday') {
            if (this.enablePic) {
              // 每次加载最新图片
              const _t = new moment().unix()
              this.instruments.forEach(i => i.imgUrl = 'http://webquotepic.eastmoney.com/GetPic.aspx?nid='+i.quoteId+'&imagetype=ZXGINDEX&rnd=68446&_t=' + _t)
            } else {
              this.listQuotations()
            }
          }
          console.log('开始刷新行情数据')
        }, 1000 * 15)
      } else {
        clearInterval(this.intervalId)
        console.log('结束刷新行情数据：' + this.intervalId)
      }
    },
    enablePic(val) {
      if (val) {
        // 每次加载最新图片
        const _t = new moment().unix()
        this.instruments.forEach(i => i.imgUrl = 'http://webquotepic.eastmoney.com/GetPic.aspx?nid='+i.quoteId+'&imagetype=ZXGINDEX&rnd=68446&_t=' + _t)
      } else {
        this.instruments.forEach(i => i.imgUrl = '')
      }
    }
  },
  computed: {
    imgSrcs() {
      return this.instruments.map(i => i.imgUrl)
    }
  },
  methods: {
    flip() {
      this.$emit('flip')
    },
    getColor(val) {
      if (val > 0)
        return '#fd8181'
      if (val < 0)
        return '#86d59a'
      return ''
    },
    get(url) {
      return new Promise((resolve, reject) => {
        axios.get(url).then(data => {
          resolve(data.data)
        }).catch(err =>{
          reject(err.data)
        })
      })
    },
    listInstruments() {
      window.API.listInstruments((instruments) => {
        this.instruments = instruments || []
      })
    },
    queryInstruments(inputValue) {
      if (inputValue.length > 0) {
        const url = 'https://searchapi.eastmoney.com/api/suggest/get?input=' + inputValue + '&type=14&token=D43BF722C8E33BDC906FB84D85E326E8&count=6'
        axios.get(url).then(data => {
          this.queryResult = data.data.QuotationCodeTable.Data
        })
      } else {
        this.queryResult = []
      }
    },
    listQuotations() {
      const indexQuoteIds = ['1.000001', '0.399001', '0.399006']
      const instrumentQuoteIds = this.instruments.map(i => i.quoteId)
      const quoteIds = indexQuoteIds.concat(instrumentQuoteIds).join(',')
      const url = 'https://push2.eastmoney.com/api/qt/ulist.np/get?secids=' + quoteIds + '&fields=f17,f16,f15,f2,f12,f14,f3,f18,f4'
      axios.get(url).then(data => {
        const quotations = data.data.data.diff
        const indexCodes = ['000001', '399001', '399006']
        const instrumentCodes = this.instruments.map(i => i.code)
        this.indexQuotations = quotations.filter(i => indexCodes.indexOf(i.f12) > -1)
        this.quotations = quotations.filter(i => instrumentCodes.indexOf(i.f12) > -1)
        this.updateTime = new moment().format('YYYY-MM-DD HH:mm:ss')
      })
    },
    showQueryItem(queryItem) {
      const codes = this.instruments.map(i => i.code)
      return codes.indexOf(queryItem.Code) == -1
    },
    addInstrument(queryItem) {
      const instrument = {
        code: queryItem.Code,
        name: queryItem.Name,
        quoteId: queryItem.QuoteID,
        type: queryItem.SecurityTypeName
      }
      this.instruments.push(instrument)
      window.ipcRenderer.send('saveInstruments', JSON.parse(JSON.stringify(this.instruments)))
      this.listQuotations()
    },
    removeInstrument(code) {
      const index1 = this.instruments.findIndex(i => i.code === code)
      const index2 = this.quotations.findIndex(i => i.f12 === code)
      this.instruments.splice(index1, 1)
      this.quotations.splice(index2, 1)
      window.ipcRenderer.send('saveInstruments', JSON.parse(JSON.stringify(this.instruments)))
    },
    formatValue(code, value) {
      const type = this.instruments.filter(i => i.code === code)[0].type
      if (type !== '基金')
        return (value / 100).toFixed(2)
      return (value / 1000).toFixed(3)
    },
    formatPercent(value) {
      return (value / 100).toFixed(2) + '%'
    },
    getInstrumentName(name) {
      if (name.length < 5) {
        return name
      } else {
        if (/^[0-9a-zA-Z]*$/.test(name.replaceAll(' ', ''))) {
          return name.slice(0, 5) + '...'
        } else {
          return name.slice(0, 3) + '...'
        }
      }
    },
    getQueryInstrumentName(name) {
      if (name.length < 10) {
        return name
      } else {
        if (/^[0-9a-zA-Z]*$/.test(name.replaceAll(' ', ''))) {
          return name.slice(0, 12) + '...'
        } else {
          return name.slice(0, 8) + '...'
        }
      }
    }
  }
}
</script>

<style scoped>
.box-card {
  width: 400px;
  height: 426px;
  border: none;
  border-radius: 10px;
  background-color: rgba(255, 255, 255, 0.3);
  color: rgba(255, 255, 255, 0.9);
}
.icon-container1 {
  float: right;
  margin-right: -10px;
  cursor: pointer;
  margin-top: -10px;
}
.icon-container2 {
  padding: 4px 0;
  border-radius: 5px;
  text-align: right;
}
.icon1, .icon2, .icon3, .icon4, .icon5, .icon6, .icon7 {
  cursor: pointer;
}
.icon1, .icon2 {
  padding-right: 8px;
}
.search-container {
  height: 32px;
  margin: 9px 0;
}
.icon5 {
  padding: 6px 6px 6px 0;
}
.input {
  width: 334px;
}
.icon:hover {
  color: rgba(255, 255, 255, 0.3);
}
.index-container {
  width: 100%;
}
:deep(.el-divider--horizontal) {
  margin: 10px 0 6px 0;
  color: rgba(255, 255, 255, 0.9);
}
:deep(.el-input__inner) {
  background-color: rgba(0, 0, 0, 0.1);
  border: none;
  border-radius: 16px;
  color: rgba(255, 255, 255, 0.9);
}
:deep(.el-input) {
  --el-input-focus-border: rgba(255, 255, 255, 0);
}
.th {
  font-weight: bold;
  padding: 8px;
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 5px 5px 0 0;
}
.th, .tr {
  width: 100%;
}
.tr {
  height: 30px;
}
.tbody {
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 0 0 5px 5px;
  padding: 8px;
}
.container-out {
  height: 185px;
  position: relative;
  overflow: hidden;
}
.container-in {
  position: absolute;
  left: 0;
  top: 0;
  right: -15px;
  bottom: 0;
  overflow-x: hidden;
  overflow-y: scroll;
}
.td4, .td5 {
  font-weight: bold;
}
:deep(.el-image-viewer__wrapper) {
  left: -415px;
  top: -274px
}
</style>